package com.yd.app.service.mobile.userService;

import com.yd.app.mapper.UserMapper;
import com.yd.app.service.common.BaseService;
import com.yd.app.service.mobile.messageService.MMessageService;
import com.yd.app.service.pc.permissionService.PermissionService;
import com.yd.app.service.ruanwei.interfacej.SmsClientSend;
import com.yd.app.util.BusinessException;
import com.yd.app.util.LoginInfoException;
import com.yd.app.util.SmsModelUtil;
import com.yd.domain.business.Message;
import com.yd.domain.commom.PageModel;
import com.yd.domain.searchParam.UserSearchParam;
import com.yd.domain.sys.DicEnum;
import com.yd.domain.sys.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;


@Service
public class MUserService extends BaseService{
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PermissionService permissionService;
    @Value("${sms.url}")
    private String sms_url;
    @Value("${sms.ID}")
    private String sms_ID;
    @Value("${sms.account}")
    private String sms_account;
    @Value("${sms.psw}")
    private String sms_psw;
    @Autowired
    private MMessageService messageService;
    //登录密码校验
    public User login(String userName, String password) throws Exception {
        User userInfo = userMapper.getUserInfoByUserName(userName);
        if (userInfo != null) {
            System.out.println("paw=="+passwordEncoding(password, userInfo.getId()));
            // 密码验证
            if (passwordEncoding(password, userInfo.getId()).equals(userInfo.getPassword())){
                //获取权限code集合
                List<String>listCode=userMapper.getUserPermCode(userInfo.getId());
                if(listCode!=null){
                    userInfo.setPermCodeList(listCode);
                }
                return userInfo;
            } else {
                throw new LoginInfoException(userName);
            }
        } else {
            throw new LoginInfoException(userName);
        }
    }
    /**
     * 获取加密后的密码
     * @param userId 用户id
     * @return
     */
    public User getUserById(String userId) {
        User user=userMapper.getUserById(userId);
        return user;
    }

    //注册用户
    public String userRegister(User user) throws BusinessException {
        String registCode="";
        //验证该用户名是否已经存在
        if(!StringUtils.isEmpty(user.getUserName())){
            int num=userMapper.getUserByUserName(user.getUserName());
            if(num>0){
                throw new BusinessException(500,"该用户名已存在!");
            }else{
                registCode=user.getId().toUpperCase();
                user.setRegistCode(registCode);//生成注册码
                user.setPassword(passwordEncoding(user.getPassword(), user.getId()));//设置用户密码
                userMapper.userRegister(user);//写入数据库
                //短信通知相关人员
                String userName=user.getUserName();
                String companyName=user.getCompanyName();
                List<User> users=permissionService.getUserByPermCode(DicEnum.PERM_CODE.USER_REG_RECEIVE);
                for(User u:users){
                    String msgCount= SmsModelUtil.USER_REG(userName,companyName);
                    String str= SmsClientSend.sendSms(sms_url,sms_ID,sms_account,sms_psw,u.getPhone(),msgCount );
                    Message message =new Message();
                    message.setPublishUser(user.getId());
                    message.setContent(msgCount);
                    message.setToken(messageService.getToken(u.getId(),user.getId()));
                    message.setPublishTime(new Date());
                    message.setReceiveUser(u.getId());
                    messageService.addMessage(message);
                }
            }
        }
        return registCode;//返回注册码
    }

    // 通过id删除用户信息
    public void deleteUserById(String userId) {
        userMapper.deleteUserById(userId);
    }

    //修改用户信息
    public void userUpdate(User user) throws BusinessException {
        if(!StringUtils.isEmpty(user.getId())){
            user.setPassword(passwordEncoding(user.getPassword(), user.getId()));//设置用户密码
            userMapper.userUpdate(user);
        }
    }
    //查询用户列表数据
    public PageModel userList(UserSearchParam param, int pageIndex, int pageSize) {
        PageModel pm=new PageModel();
        List<User> returnList=userMapper.getUserList(param,getStartRow(pageIndex,pageSize),pageSize);
        int count=0;
        if(pageIndex==1){
            //查询总条数
            count=userMapper.getUserListCount(param);
        }
        pm.setCount(count);
        pm.setList(returnList);
        return  pm;
    }
    /**
     * @Author: zy
     * @Desc: 根据注册码查询用户信息
     * @Date:  2018/3/23
     * @Param
     */
    public User getUserByReg(User user) {
        User u=userMapper.getUserByReg(user);
        return u;
    }
    //修改密码
    public void updateUserPwd(String id, String oldPwd, String newPwd) throws BusinessException {
        User u=userMapper.getUserById(id);
        if(!passwordEncoding(oldPwd,id).equals(u.getPassword())){

            throw new BusinessException(500,"原密码不正确!");
        }
        try {
            userMapper.updatePwd(id,passwordEncoding(newPwd,id));
        } catch (Exception e) {
            throw new BusinessException(500,"密码修改失败!");
        }

    }
}
